import axios from 'axios';
import querystring from 'querystring';

const isClient = process.env.VUE_APP_ENV === 'client';
const isFront = process.env.VUE_APP_ENV === 'front';
const baseURL = process.env.VUE_APP_AXIOS_OTHER_HOST;

const _axios = axios.create({
  baseURL: `/`,
  timeout: 6000,
  withCredentials: true
});

_axios.interceptors.request.use(config => {
  // 客户端发起的所有请求都需要加上请求头frontOpStation参数
  if (isFront || isClient) {
    const opStation = sessionStorage.getItem('opStation') || '';
    config.headers.appType = opStation.appType;
    config.headers.version = opStation.version;
  }

  return config;
}, error => {
  console.log(`axiosOther request err`, error);
  return Promise.reject(error);
});

_axios.interceptors.response.use(response => {
  if (response.status >= 400 && response.data.errors.length) {
    let message = '';
    response.data.errors.forEach(error => {
      message += `${error.message}\n`;
    });
    return Promise.reject(message);
  }
  return response.data;
}, (error) => {
  const message = `${error.message}, url: ${error.config}`;
  console.log(`axiosOther response err. ${message}`);
  return Promise.reject(new Error(`axiosOther response err. ${message}`));
});

export default {
  async request(url, options = { }) {
    const defaultOptions = {
      method: 'get',
      data: {}
    };
    options = { ...defaultOptions, ...options };
    const { method, data, headers } = options;
    if (data) {
      const searchstring = querystring.stringify(data);
      url += searchstring ? `?${searchstring}` : '';
    }
    const params = {
      url,
      method,
      headers,
      data,
    };
    return _axios(params);
  },
  async post(url, data = {}, options = {}) {
    options.method = 'post';
    options.data = data;
    options.headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    };
    return this.request(url, options);
  },
  async get(url, data = {}, options = {}) {
    options.data = data;
    options.headers = {
      'Content-Type': 'application/json;charset=UTF-8'
    };
    return this.request(url, options);
  }
};